<?php

namespace App\Services;


use Endroid\QrCode\Bacon\ErrorCorrectionLevelConverter;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use Intervention\Image\ImageManagerStatic as Image;
use Util\Common;

class FileService
{
    /**上传图片并生成缩略图
     * @param $file
     * @return array
     */
    public function uploadImg($file,$width=200,$height=200):array{
        $fileName = $file->getClientFilename();  // 获取文件名
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);  // 获取文件后缀
        //临时绝对路径
        $realPath = $file->getPath();
        $date = date('Ymd',time());
        $filename = uniqid().time().'.'.$ext;
        $publicPath =  BASE_PATH.'/public';
        if (!is_dir($publicPath.'/upload/'.$ext.'/'.$date)) {
            mkdir($publicPath.'/upload/'.$ext.'/'.$date,0777,true);
        }
        $file->moveTo($publicPath.'/upload/'.$ext.'/'.$date.'/'.$filename);
        chmod($publicPath.'/upload/'.$ext.'/'.$date.'/'.$filename, 0644);  // 设置文件权限为 644
        $thumb_path = $publicPath.'/upload/thumb/';
        $thumb_name = $thumb_path.'/'.$filename;
        if (!is_dir($thumb_path)) {
            mkdir($thumb_path,0777,true);
        }
        $data['url']  = Common::MAIN_HOST.'/upload/'.$ext.'/'.$date.'/'.$filename;
        $imgBig = Image::make($publicPath.'/upload/'.$ext.'/'.$date.'/'.$filename);
        $imgBig->fit($width, $height)->save($thumb_name);
        $data['thumb'] = Common::MAIN_HOST.'/upload/thumb/'.$filename;
        return $data;
    }

    /**根据文件名生成zip
     * @param $files
     * @return string
     */
    public function uploadZip($files){
        $zip = new \ZipArchive();
        $publicPath = BASE_PATH . '/public'; // public目录的路径。确保BASE_PATH已正确定义
        $zipFilePath = '/upload/zips/'; // 保存ZIP文件的目录，确保此目录已存在且有写权限
        $zipFileName = uniqid().'.zip'; // ZIP文件的名称
        $fullZipPath = $publicPath . $zipFilePath . $zipFileName;
        try{
            if ($zip->open($fullZipPath, \ZipArchive::CREATE) === TRUE) {
                foreach ($files as $file) {
                    $zip->addFile($file, basename($file));
                }
                $zip->close();
                $downloadLink = $fullZipPath;
                return $downloadLink;
            } else {
                return '';
            }
        }catch (\Exception $e){
            return '';
        }
    }

    /**设置后台背景图
     * @param $file
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function backImg($file):array{
        $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
        $fileMimeType = $file->getMimeType();

        if (!in_array($fileMimeType, $allowedMimeTypes)) {
           return [];
        }
        $fileName = $file->getClientFilename();  // 获取文件名
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);  // 获取文件后缀
        //临时绝对路径
        $realPath = $file->getPath();
        $date = date('Ymd',time());
        $filename = 'back_admin_img'.'.'.$ext;
        $publicPath =  BASE_PATH.'/public/upload/';
        $file->moveTo($publicPath.$filename);
        $key = 'back_admin_img';
        $data['url']  = Common::MAIN_HOST.'/upload/'.$filename;
        redis()->set($key,$data['url']);
        return $data;
    }

    /**获取文件大小
     * @param $num
     * @return string
     */
    public static function getFilesize($num):string{
        $p = 0;
        $format='bytes';
        if($num>0 && $num<1024){
            $p = 0;
            return number_format($num).' '.$format;
        }
        if($num>=1024 && $num<pow(1024, 2)){
            $p = 1;
            $format = 'KB';
        }
        if ($num>=pow(1024, 2) && $num<pow(1024, 3)) {
            $p = 2;
            $format = 'MB';
        }
        if ($num>=pow(1024, 3) && $num<pow(1024, 4)) {
            $p = 3;
            $format = 'GB';
        }
        if ($num>=pow(1024, 4) && $num<pow(1024, 5)) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 2).' '.$format;
    }

    /**
     * @param string $params
     * @return array
     */
    public static function creatCode(string $deviceId,bool $is_save = false): array
    {
        $writer = new PngWriter();
        /*支付参数二维码*/
        $codeUrl = Common::MAIN_HOST.'/qrcode_parse?sn='.$deviceId;
        // Create QR code
        $qrCode = QrCode::create($codeUrl)
            ->setEncoding(new Encoding('UTF-8'))
            ->setSize(200)
            ->setMargin(10)
            ->setForegroundColor(new Color(0, 0, 0))
            ->setBackgroundColor(new Color(255, 255, 255));
        // Create generic logo
//        $logo = Logo::create('logo地址')
//            ->setResizeToWidth(50);

        // Create generic label
        $label = Label::create('ID:'.$deviceId)
            ->setTextColor(new Color(0, 0, 0));//标题中颜色-红-绿-蓝

        $result = $writer->write($qrCode, null, $label);
        // Directly output the QR code
        // header('Content-Type: ' . $result->getMimeType());

        // Save it to a file
        if($is_save){
            $data['url'] = $result->saveToFile(BASE_PATH . '/public/upload/img/'.$deviceId.'.png');//二维码保存地址
        }
    // Generate a data URI to include image data inline (i.e. inside an <img> tag)
       $dataUri = $result->getDataUri();
        $data['base'] = $dataUri;
       return $data;
}

}
